<?php

/**
 * @Author: wuchenge
 * @Date: 2020-11-30 18:31:19
 * @email: ligui0506@sina.com
 * @descript: 权限相关服务
 */

namespace App\Services;

use App\Libraries\Utils;
use App\Models\Rbac\Node;
use App\Models\Rbac\Role;
use App\Models\Rbac\RoleAdmin;
use App\Models\Rbac\RoleNode;

class Permission
{
    public static function getNodeBy($id)
    {
        $is_supper = self::isSupper($id);

        $permissions = [];
        // 如果是超级管理员，返回所有节点
        if ($is_supper) {
            $field = ['id', 'name', 'title', 'pid', 'sort'];
            $data  = Node::select($field)
                ->orderBy('sort', 'asc')
                ->get()
                ->toArray();
            $permissions = Utils::nesting($data);
        } else {
            $permissions = self::getNode($id);
        }

        return $permissions;
    }

    // 判断是否为超级管理员
    public static function isSupper($uid)
    {
        $supper = config('api.supper');
        return in_array($uid, $supper);
    }

    /**
     * 获取不是超级管理的权限
     * @param  [type] $uid [description]
     * @return [type]      [description]
     */
    public static function getNode($uid)
    {
        $roles = RoleAdmin::where('admin_id', $uid)->pluck('role_id');
        $nodes = [];
        if (!empty($roles)) {
            $nodes = array_merge($nodes, RoleNode::whereIn('role_id', $roles)->pluck('node_id')->toArray());
        }
        // 去重
        $nodes = array_values(array_flip(array_flip($nodes)));
        $field = ['id', 'name', 'title', 'pid', 'sort'];
        $nodes = Node::select($field)
            ->whereIn('id', $nodes)
            ->orderBy('sort', 'asc')
            ->get()
            ->toArray();
        if ($nodes) {
            $nodes = Utils::nesting($nodes);
        }
        return $nodes;
    }
}
